package com.tqjc.execute.thread.aysn;

import com.tqjc.execute.consts.EleLogConstants;
import com.tqjc.execute.utils.HttpPLCUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: 86195
 * @CreateTime: 2024-08-28  16:02
 * @Description: 检查电气程序对中机构日志
 * @Version: 1.0
 */
@Data
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class AysnEleLogThread extends Thread{

    private String craneName;

    private RestTemplate restTemplate;

    private String host;


    @Override
    public void run() {
        log.info("======异步打印电气程序日志线程开始,天车为：{}=======",craneName);


        try {

            String flag = HttpPLCUtils.plcReadbc(restTemplate, host, craneName, "自动对中屏蔽", false);
            if("true".equalsIgnoreCase(flag)){
                log.info("异步打印电气程序日志线程,天车：{}，当前对中机构已被屏蔽,不需要进行对中点位监控",craneName);
                log.info("======异步打印电气程序日志线程结束,天车为：{}=======",craneName);
                return;

            }
            long start = System.currentTimeMillis();
            while (true){

                String suffix = "11C北".equals(craneName) ? "A" : "B";

                for (String label : EleLogConstants.ELE_LOG_LABEL_LIST) {
                    try {
                        String val = HttpPLCUtils.plcReadbc(restTemplate, host, "对中机构", label + suffix, false);
                        log.info("异步打印电气程序日志线程，天车：{},当前标签为：{},监听的的值为：{}",craneName,label + suffix,val);
                    } catch (Exception e){
                        log.error("异步打印电气程序日志线程，天车：{},当前标签为：{},监听点位信息出现异常",craneName,label + suffix,e);
                    }


                }
                String endLabel = "对中状态" + suffix;
                String endLabelVal = HttpPLCUtils.plcReadbc(restTemplate, host, "对中机构", endLabel, false);
                if("2".equals(endLabelVal)){
                    log.info("异步打印电气程序日志线程,天车：{},对中状态已为2，不再监听电气对中点位",craneName);
                    break;
                }
                if(System.currentTimeMillis() - start > 30*1000){
                    log.info("异步打印电气程序日志线程,天车：{},时长已运行超过30秒",craneName);
                    break;
                }
            }

        } catch (Exception e){
            log.error("异步打印电气程序日志线程运行出现异常,天车为：{}",craneName,e);
        }

        log.info("======异步打印电气程序日志线程结束,天车为：{}=======",craneName);

    }
}
